export function setLocalStorage<T>(key: string, value: T) {
  if (typeof value === 'string') {
    localStorage.setItem(key, value);
  } else {
    localStorage.setItem(key, JSON.stringify(value));
  }
}
export function getLocalStorage<T>(key: string): T | string {
  const result = localStorage.getItem(key);
  if (!result) return '';
  try {
    return JSON.parse(result);
  } catch (error) {
    return result;
  }
}

export function parseWsMsg(msg: string) {
  if (!msg) return {};
  const arrs = msg.split('&');
  const info: any = {};
  arrs.forEach(arr => {
    const value = arr.split('=');
    if (value && value.length === 2) {
      info[value[0]] = value[1];
    }
  });
  return info;
}

/**
 * 保存本地信息
 * @param key
 * @param value
 * @param vaildTime 有效时间
 */
export function setSessionStorage(key: string, value: any, vaildTime: number = 3600 * 24) {
  if (value === undefined || value == null) {
    sessionStorage.removeItem(key);
    return;
  }
  let result = {
    // update_time: new Date().getTime(),
    expiration_time: new Date().getTime() + vaildTime,
    data: value,
  };

  sessionStorage.setItem(key, JSON.stringify(result));
}

/**
 * 获取缓存数据
 * @param key
 * @returns
 */
export function getSessionStorage<T, K>(key: string, defaultValue: K): T | K {
  const data = sessionStorage.getItem(key);
  if (!data) {
    return defaultValue;
  }
  const result = JSON.parse(data);
  if (result.expiration_time - new Date().getTime() > 0) {
    return result.data;
  } else {
    sessionStorage.removeItem(key);
    return defaultValue;
  }
}

export function testPhone(phone: string): boolean {
  return /^1[3|4|5|6|7|8|9]{1}[0-9]{9}$/g.test(phone);
}

export function utf8ToGbk(utf8Text: string) {
  return utf8Text.replace(/[\u0080-\uFFFF]/gu, function (char) {
    return String.fromCharCode(char.charCodeAt(0) % 256);
  });
}
